/**
 * @Title:  AuthMechanismActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-1-5 上午11:24:06 
 * @version:  V1.0 
 */
package artid.com.arttogo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.ArtListDetailAdapter;
import artid.com.arttogo.adapter.ScanMiroViewAdapter;
import artid.com.arttogo.bean.ArtComment;
import artid.com.arttogo.bean.ArtFavorite;
import artid.com.arttogo.bean.ArtShownum;
import artid.com.arttogo.bean.ArtistFollow;
import artid.com.arttogo.bean.OneStateIntParser;
import artid.com.arttogo.bean.RqCertif;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.bean.ShowPhoto;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.BitmapCache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.AlertUtils;
import artid.com.arttogo.utils.Config;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.MyListView;
import artid.com.arttogo.view.PicDotView;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableScrollView;

import static artid.com.arttogo.R.id.on;

/**
 * 扫码描证书的二维码，跳转的页面
 * 
 * @author 熊彬
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */
public class ScanCertiActivity extends BaseActivity implements OnClickListener {
//	public static Bitmap DOT_PIC = null;
	private Context mContext;
    TextView  mTextMoreInfo;
	private ImageView back;
	//					↓主图    证书图   点赞       取消点赞    收藏     取消收藏
	private ImageView cImage, pImage, imgLike, imgUnlike, imgColl, imgUncoll;
	View viewlike, viewCollect;
	//					介绍   证书编号   标题   点赞数量   收藏数量  鉴证机构
	private TextView config, proDnum, title, textlike, textsc, textjzjg;
	private ImageLoader mImageLoader;
	ImageView imageAuth;
	MyListView mlist;
	String id = "";
	//评论
	EditText editComment;
	//分享
	ImageView mImgShare;
	PullToRefreshLayout mPullLayout;
	int pageIndex = 1, pagesize = 10;
	PullableScrollView mscroll;
	View hideView;
	RqCertif codeItem = null;
	View viewPic;
	//分享信息的类
	ShareItem shareItem;
	String srcImg = "", picname = "";
	String uid = "";
	ArtListDetailAdapter adapter;
	String messid = "";
	Boolean isReplyPerson = false;
	String commentId = "";
	private int width;
	View downHalf;
	String photoinfo = "";
	ShowPhoto photoItem = new ShowPhoto();
	//机构，机构编号的视图
	View organ, organCode;
	MyListView mlistMicro;
	//微观图的adapter
	ScanMiroViewAdapter adapterMicro;
	TextView mtextArtName, mtextArtist, mtextAuther;// auther是标注作者
	List<ShowPhoto> listMicroPhotos;// 微观图集合
	View gz, qxgz;
	View mViewshowMain;
	MySharedPreferences sharedPreferences;
	String code;
	String shareInfo = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scancertif);
		mContext = ScanCertiActivity.this;
		sharedPreferences = MySharedPreferences
				.getMySharedPreferences(mContext);
		mViewshowMain = (View) findViewById(R.id.scan_showmain);
        mTextMoreInfo = (TextView)findViewById(R.id.view_more_info);
		gz = (View) findViewById(R.id.scan_gz);
		qxgz = (View) findViewById(R.id.scan_qxgz);
		mtextArtName = (TextView) findViewById(R.id.scan_art_name);
		mlistMicro = (MyListView) findViewById(R.id.scan_microview);
		mtextArtist = (TextView) findViewById(R.id.scan_artist);
		mtextAuther = (TextView) findViewById(R.id.scan_creater);
		organ = (View) findViewById(R.id.coldet_org);
		organCode = (View) findViewById(R.id.coldet_org_code);
		downHalf = (View) findViewById(R.id.col_down_half);
		downHalf.setVisibility(View.INVISIBLE);
		VolleyBasic.showLoding(ScanCertiActivity.this);
		hideView = (View) findViewById(R.id.collection_det_hideview);
		messid = getIntent().getExtras().getString("messid");
		if (messid == null) {
			messid = "";
		}
		code = getIntent().getExtras().getString("code");
		shareItem = new ShareItem();
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());

		back = (ImageView) findViewById(R.id.back_btn);
		imageAuth = (ImageView) findViewById(R.id.image_is_auth);
		mscroll = (PullableScrollView) findViewById(R.id.collection_detail_scroll);
		imgLike = (ImageView) findViewById(R.id.img_artwork_det_like);
		viewlike = (View) findViewById(R.id.view_like);
		viewlike.setOnClickListener(this);
		imgUnlike = (ImageView) findViewById(R.id.img_artwork_det_unlike);
		imgColl = (ImageView) findViewById(R.id.icon_collect_sel);
		viewCollect = (View) findViewById(R.id.view_collect);
		viewCollect.setOnClickListener(this);
		imgUncoll = (ImageView) findViewById(R.id.icon_collect_unsel);
		mImgShare = (ImageView) findViewById(R.id.share_collection_detail);
		mImgShare.setVisibility(View.VISIBLE);

		cImage = (ImageView) findViewById(R.id.iv_coll_img);
		cImage.setOnClickListener(this);
		pImage = (ImageView) findViewById(R.id.iv_certific);
		config = (TextView) findViewById(R.id.tv_coll_config);
		proDnum = (TextView) findViewById(R.id.tv_coll_product);
		title = (TextView) findViewById(R.id.tittle_text);
		textlike = (TextView) findViewById(R.id.artdetal_z);
		textsc = (TextView) findViewById(R.id.artdetal_sc);
		textjzjg = (TextView) findViewById(R.id.artdetal_jzjg);
		editComment = (EditText) findViewById(R.id.artdet_comment_edit);
		editComment.setOnClickListener(this);
		editComment
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					public boolean onEditorAction(TextView v, int actionId,
												  KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE
								|| actionId == EditorInfo.IME_ACTION_SEARCH
								|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
							if (TextUtils.isEmpty(editComment.getText()
									.toString())) {
								Config.showTip(ScanCertiActivity.this, "评论不能为空");
								return false;
							}
							if (TextUtils.isEmpty(editComment.getHint()
									.toString())) {
								isReplyPerson = false;
							}
							if (isReplyPerson) {
								Replycomment(commentId);
							} else {
								reqArtReplycomment();
							}

							return false;
						}
						return false;
					}
				});
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		mlist = (MyListView) findViewById(R.id.list_artdetal);
		mPullLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		mPullLayout.setVisibility(View.INVISIBLE);
		mPullLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				pageIndex = 1;
				reqData();

			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				if (adapter.listdata.size()>(pagesize-1)) {
					pageIndex++;
				}
				//评论数据
				reqCommentData();
			}
		});

		adapter = new ArtListDetailAdapter(mContext);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		width = dm.widthPixels;
		reqcode(code);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!TextUtils.isEmpty(id)) {
			reqisLike(id);
		}
		if (AppUtil.getUser().isLogin()&&codeItem!=null){
            reqcode(code);
        }
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		DOT_PIC = null;
	}

	//请求证书的数据，存在本地用于扫码的历史数据
	void reqcode(final String code) {
		VolleyBasic.getInstance(ScanCertiActivity.this).post(Cache.rqCode,
				VolleyMap.getInstance().rqCode(code), RqCertif.class,
				new VolleyCallback() {

					@SuppressLint("NewApi")
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						RqCertif reqitem = (RqCertif) vd.getData();
						codeItem = reqitem;
						//设置数据
						reqData();
						//把请求的保存在本地
						try {
							String strjson = sharedPreferences.getValue("his",
									"");
							JSONObject jsonObject;
							JSONArray jsArray = null;
							if (TextUtils.isEmpty(strjson)) {
								jsonObject = new JSONObject();

								jsonObject.put("data", new JSONArray());
								jsArray = jsonObject.getJSONArray("data");

							} else {

								jsonObject = new JSONObject(strjson);
								jsArray = jsonObject.optJSONArray("data");

							}

							if (strjson.contains(reqitem.getCode())) {
								for (int i = 0; i < jsArray.length(); i++) {
									JSONObject jsitem = jsArray.getJSONObject(i);
									if (jsitem.optString("title").contains(reqitem.getCode())) {
										jsArray.remove(i);
									}
									
								}
							}
								
							
								//生成新的
								JSONObject item = new JSONObject();
								String title = "";
								title = reqitem.getTitle() + " / "
										+ reqitem.getCode();
								String auher = reqitem.getAuthor();
								if (TextUtils.isEmpty(auher)) {
									auher = "";
								}

								item.put("title", title);
								item.put("auther", auher);
								SimpleDateFormat formatter = new SimpleDateFormat(
										"yyyy年MM月dd日    HH:mm");
								Date curDate = new Date(System
										.currentTimeMillis());// 获取当前时间
								String strTime = formatter.format(curDate);
								item.put("time", strTime);
								item.put("code", code);
								
								//把新得到的放在第一个
								JSONArray newarr = new JSONArray();
								newarr.put(item);
								for (int i = 0; i < jsArray.length(); i++) {
									newarr.put(jsArray.getJSONObject(i));
								}
//								jsArray.put(item);
								jsonObject = new JSONObject();
								jsonObject.put("data", newarr);
								Log.e("jsonall", jsonObject.toString());
								sharedPreferences.setValue("his",
										jsonObject.toString());

						

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}
	PicDotView dotView;
	//设置数据
	void reqData() {

		final RqCertif item = codeItem;
		if (item.getIs_equipment().equals("2")) {
			mlistMicro.setVisibility(View.GONE);
		}
		Glide.with(mContext).load(item.getAllimge() + AppUtil.picWidthUrl)
				.asBitmap().into(new SimpleTarget<Bitmap>() {
					@Override
					public void onResourceReady(Bitmap resource,
							GlideAnimation<? super Bitmap> glideAnimation) {
						ViewGroup.LayoutParams lp = cImage.getLayoutParams();
						int w = resource.getWidth();
						int h = resource.getHeight();
						
						lp.width = width;
						lp.height = h * width / w;

						cImage.setLayoutParams(lp);

						cImage.setMaxWidth(width);
						cImage.setMaxHeight((int) (width * 20));
						cImage.setImageBitmap(resource);

						
						 dotView = (PicDotView) findViewById(R.id.scan_certi_picdot);
						 if (codeItem.getIs_phone().equals("2")) {
							 dotView.setIsRound(false);
						}else {
							dotView.setIsRound(true);
						}
						
						if (item.getIs_equipment().equals("2")) {
							dotView.setVisibility(View.GONE);
						}
						dotView.resetView();
						dotView.setLayoutParams(lp);
						listMicroPhotos = new ArrayList<ShowPhoto>();

						int fullwidth = width;

						try {
							fullwidth = Integer.valueOf(codeItem.getFullwidth());
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(mContext, "未得到图片的宽", Toast.LENGTH_SHORT).show();
							return;
						}
						/**
						 * 原图除以屏幕
						 */
						double picScrn = (double) fullwidth / width;
						int microIndex = 1;
                        //描点、添加微观点信息
						addDot:for (RqCertif.PointImg index : codeItem.getList()) {
							String imgString = index.getImgurl();
							if (!TextUtils.isEmpty(imgString)
									& !imgString.contains("null")) {

								dotView.addDotXy(index.getX(), index.getY(),
										picScrn, imgString);
								// dotLayout.addView(iv1);
								ShowPhoto item = new ShowPhoto();
								item.setName("第" + String.valueOf(microIndex)
										+ "张微观图：");
								microIndex++;
								item.setUrl(index.getImgurl());
								item.setInfo(index.getText());
								listMicroPhotos.add(item);

							}

						}
                        //如果没有登录只加载一个点
                        if (!AppUtil.getUser().isLogin()){
                            ArrayList<RqCertif.PointImg> newlist = new ArrayList<RqCertif.PointImg>();
                            newlist.add(codeItem.getList().get(0));
                            codeItem.setList(newlist);
                            mTextMoreInfo.setVisibility(View.VISIBLE);
                            mTextMoreInfo.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(ScanCertiActivity.this,LoginActivity.class);
                                    startActivity(intent);

                                }
                            });

                        }else {
                            mTextMoreInfo.setVisibility(View.GONE);
                        }
						photoItem.setList(listMicroPhotos);
						dotView.invalidate();
						mViewshowMain.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
							
								//准备带点的微观图，设置全局bitmap
//								PicDotView dotview2 = dotView; 
//								DOT_PIC =  dotview2.getDotBitmap(resource);
								
								ShowPhoto pitem = new ShowPhoto();
								List<ShowPhoto> listMainAndMicro = new ArrayList<ShowPhoto>();
								if (TextUtils.isEmpty(item.getArtpointurl())) {
									pitem.setUrl(item.getAllimge());
								}else {
									pitem.setUrl(item.getArtpointurl());
								}
							
								listMainAndMicro.add(pitem);
								listMainAndMicro.addAll(listMicroPhotos);
								ShowPhoto allitem = new ShowPhoto();
								allitem.setList(listMainAndMicro);
								Intent intent = new Intent(
										ScanCertiActivity.this,
										PhotoActivity.class);
								intent.putExtra("item", allitem);
								startActivity(intent);
							}
						});
						
						if (codeItem.getIs_phone().equals("2")) {
							adapterMicro = new ScanMiroViewAdapter(mContext,false);
						}else {
							adapterMicro = new ScanMiroViewAdapter(mContext,true);
						}
						
						adapterMicro.setdata(codeItem.getList());
						mlistMicro.setAdapter(adapterMicro);
						mlistMicro
								.setOnItemClickListener(new OnItemClickListener() {

									@Override
									public void onItemClick(
											AdapterView<?> arg0, View arg1,
											int arg2, long arg3) {
										// TODO Auto-generated method stub
										AlertUtils.scanAlertDialog(mContext,
												adapterMicro.getImgurl(arg2),
												"", "",
												adapterMicro.getInfo(arg2),
												width, listenerShowMicro(arg2));
									}
								});
						dotView.setOnClick(new PicDotView.onDotClickListener() {

							@Override
							public void onClick(int i) {
								// TODO Auto-generated method stub
                                if (AppUtil.getUser().isLogin()||i==0){
                                    AlertUtils.scanAlertDialog(mContext,
                                            adapterMicro.getImgurl(i), "", "",
                                            adapterMicro.getInfo(i), width,
                                            listenerShowMicro(i));
                                }else {
                                    ToastUtil.toast(mContext,"请登录后查看");
                                }
							}
						});
						mtextArtName.setText(codeItem.getTitle());
						if (TextUtils.isEmpty(codeItem.getRealname())) {
							mtextArtist.setVisibility(View.GONE);
							;
						} else {
							mtextArtist.setText(codeItem.getRealname());
						}
						mtextAuther.setText(codeItem.getAuthor());
						//关注
						String isfollow = item.getIs_follow();
						gz.setOnClickListener(listenerGz(
								codeItem.getArtist_id(), true));
						qxgz.setOnClickListener(listenerGz(
								codeItem.getArtist_id(), false));
						if (isfollow.equals("1")) {
							qxgz.setVisibility(View.VISIBLE);
							gz.setVisibility(View.GONE);
						} else {
							qxgz.setVisibility(View.GONE);
							gz.setVisibility(View.VISIBLE);
						}
						//点赞
						String isLike = item.getIs_art_commend();
						if (!item.getIs_artist().equals("1")) {
							qxgz.setVisibility(View.GONE);
							gz.setVisibility(View.GONE);
						}
						if (isLike.equals("1")) {
							// setColLikeComment(true, textlike);
							imgLike.setVisibility(View.VISIBLE);
							imgUnlike.setVisibility(View.GONE);
						} else {
							imgLike.setVisibility(View.GONE);
							imgUnlike.setVisibility(View.VISIBLE);
							// setColLikeComment(false, textlike);
						}

					}
				});
		srcImg = item.getPic_url();
		picname = item.getTitle();
		photoinfo = item.getArttype() + "/" + item.getSize() + "/"
				+ item.getCreatetime();
		//分享
		shareInfo = "类别:"+item.getArttype()+";"+"尺寸:"+item.getSize()+";"+"年代:"+ item.getCreatetime()+";";
		if (item.getImgurl().contains("http")) {
			Glide.with(mContext).load(item.getImgurl() + AppUtil.picWidthUrl)
					.asBitmap().into(new SimpleTarget<Bitmap>() {
						@Override
						public void onResourceReady(Bitmap resource,
								GlideAnimation<? super Bitmap> glideAnimation) {
							ViewGroup.LayoutParams lp = pImage
									.getLayoutParams();
							int w = resource.getWidth();
							int h = resource.getHeight();

							lp.width = width - Cache.dip2px(mContext, 20);
							lp.height = h * width / w;

							pImage.setLayoutParams(lp);

							pImage.setMaxWidth(width);
							pImage.setMaxHeight((int) (width * 10));
							pImage.setImageBitmap(resource);

						}
					});
			pImage.setVisibility(View.VISIBLE);
			pImage.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					ShowPhoto pitem = new ShowPhoto();
					pitem.setUrl(item.getImgurl());
					Intent intent = new Intent(ScanCertiActivity.this,
							PhotoActivity.class);
					intent.putExtra("item", pitem);
					startActivity(intent);
				}
			});
		}
		downHalf.setVisibility(View.VISIBLE);
		title.setText(item.getTitle());
		config.setText(photoinfo);
		textlike.setText("点赞  (" + item.getCommend_num() + ")");
		textsc.setText("收藏  (" + item.getFav_num() + ")");
		if (!TextUtils.isEmpty(item.getCode())) {
			proDnum.setText(item.getCode());
		} else {
			organCode.setVisibility(View.GONE);

		}
		if (!TextUtils.isEmpty(item.getOrganization())) {
			textjzjg.setText(item.getOrganization());
		} else {
			organ.setVisibility(View.GONE);
		}
		if (TextUtils.isEmpty(item.getOrganization())
				&& TextUtils.isEmpty(item.getCode())) {
			findViewById(R.id.view_coldet_activity_certif).setVisibility(
					View.GONE);
		}

		//设置分享
		shareItem = new ShareItem();
		shareItem.setTitle(item.getTitle());
		shareItem.setContent(shareInfo);
		shareItem.setUrl(item.getShareurl());
		shareItem.setImageUrl(item.getAllimge() + AppUtil.picWidthSmallUrl);
		mImgShare.setOnClickListener(this);

		id = item.getArt_id();
		if (!TextUtils.isEmpty(id)) {
			reqCommentData();
			reqisLike(id);
		}

	}

	OnClickListener listenerShowMicro(final int index) {
		return new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, PhotoActivity.class);
				intent.putExtra("item", photoItem);
				intent.putExtra(PhotoActivity.EXTRA_IMAGE_INDEX, index);
				startActivity(intent);
			}
		};
	}
	//请求关注
	void reqFollow(String id, final Boolean setFollow) {
		String state = "";
		if (setFollow) {
			state = "1";
		} else {
			state = "2";
		}
		VolleyBasic.getInstance((Activity) mContext).post(
				Cache.artistFollow,
				VolleyMap.getInstance().artistFollow(
						AppUtil.getUser().getToken(), id, state),
				ArtistFollow.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						ArtistFollow itemArtistFollow = (ArtistFollow) vd
								.getData();

						if (itemArtistFollow.getState().equals("1")) {
							if (setFollow) {
								gz.setVisibility(View.GONE);
								qxgz.setVisibility(View.VISIBLE);
							} else {
								gz.setVisibility(View.VISIBLE);
								qxgz.setVisibility(View.GONE);
							}

						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}

	//请求评论
	void reqCommentData() {
		VolleyBasic.getInstanceNoDialog(ScanCertiActivity.this).post(
				Cache.artComment,
				VolleyMap.getInstance().artComment(id,
						String.valueOf(pageIndex), String.valueOf(pagesize)),
				ArtComment.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						VolleyBasic.disMissLoding();
						mPullLayout.setVisibility(View.VISIBLE);
						// TODO Auto-generated method stub
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
						List<ArtComment> list = (List<ArtComment>) vd.getList();
						if (list.isEmpty()) {
							// Config.showTip(CollectionDetailsActivity.this,
							// "无数据");
							return;
						}
						if (pageIndex != 1) {
							adapter.addList(list);
							mlist.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> arg0,
														View arg1, int arg2, long arg3) {
									// TODO Auto-generated method stub
									String replyPreFix = "";
									replyPreFix = "@"
											+ adapter.listdata.get(arg2)
													.getRealname() + ":";
									isReplyPerson = true;
									commentId = adapter.listdata.get(arg2)
											.getMessid();
									startComment(replyPreFix);
								}
							});
							return;
						}
						mlist.setAdapter(adapter);
						adapter.setdata(list);
						mlist.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0,
													View arg1, int arg2, long arg3) {
								// TODO Auto-generated method stub
								String replyPreFix = "";
								replyPreFix = "@"
										+ adapter.listdata.get(arg2)
												.getRealname() + ":";
								isReplyPerson = true;
								commentId = adapter.listdata.get(arg2)
										.getMessid();
								startComment(replyPreFix);
							}
						});

					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						VolleyBasic.disMissLoding();
						mPullLayout.setVisibility(View.VISIBLE);
						mPullLayout.loadmoreFinish(mPullLayout.FAIL);
					}
				});
	}

	//请求点赞
	void reqLike(final String id, final Boolean setFollow) {
		String state = "";
		if (setFollow) {
			state = "1";
		} else {
			state = "2";
		}
		VolleyBasic.getInstance((Activity) mContext).post(
				Cache.artSupport,
				VolleyMap.getInstance().artSupport(id,
						AppUtil.getUser().getToken(), state), OneStateIntParser.class,
				new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						if (vd.getCode() == -99) {
							AppUtil.Logout(ScanCertiActivity.this);
							AppUtil.LoginVer(ScanCertiActivity.this);
							return;
						}
						OneStateIntParser itemArtistFollow = (OneStateIntParser) vd.getData();

						if (itemArtistFollow.getState()==1) {
							if (setFollow) {
								setColLikeComment(true, textlike);
								imgLike.setVisibility(View.VISIBLE);
								imgUnlike.setVisibility(View.GONE);
							} else {
								imgLike.setVisibility(View.GONE);
								imgUnlike.setVisibility(View.VISIBLE);
								setColLikeComment(false, textlike);
							}

						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}
	//设置收藏和点赞的文字内容
	void setColLikeComment(Boolean isUp, TextView setView) {
		String strTxt = setView.getText().toString();
		String strnum = strTxt.substring(strTxt.indexOf("(") + 1,
				strTxt.indexOf(")"));
		try {
			int num = Integer.valueOf(strnum);
			if (isUp) {
				num++;
			} else {
				num--;
			}
			if (strTxt.contains("收藏")) {
				textsc.setText("收藏  (" + String.valueOf(num) + ")");
			}
			if (strTxt.contains("点赞")) {
				textlike.setText("点赞  (" + String.valueOf(num) + ")");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}


	//请求收藏
	void reqCollect(final String id, final Boolean setCollect) {
		String state = "";
		if (setCollect) {
			state = "1";
		} else {
			state = "2";
		}
		VolleyBasic.getInstance((Activity) mContext).post(
				Cache.artFavorite,
				VolleyMap.getInstance().artFavorite(
						AppUtil.getUser().getToken(), id, state),
				ArtFavorite.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						if (vd.getCode() == -99) {
							AppUtil.Logout(ScanCertiActivity.this);
							AppUtil.LoginVer(ScanCertiActivity.this);
							return;
						}
						// TODO Auto-generated method stub
						ArtFavorite itemArtistFollow = (ArtFavorite) vd
								.getData();

						if (itemArtistFollow.getState().equals("1")) {
							if (setCollect) {
								imgColl.setVisibility(View.VISIBLE);
								imgUncoll.setVisibility(View.GONE);
								setColLikeComment(true, textsc);
							} else {
								imgColl.setVisibility(View.GONE);
								imgUncoll.setVisibility(View.VISIBLE);
								setColLikeComment(false, textsc);
							}
							// reqData();
						}

					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}
	//判断是否点赞
	void reqisLike(String id) {
		VolleyBasic.getInstanceNoDialog((Activity) mContext).post(
				Cache.artShownum,
				VolleyMap.getInstance().artShownum(
						AppUtil.getUser().getToken(), id), ArtShownum.class,
				new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						if (vd.getCode() == -99) {
							AppUtil.Logout(ScanCertiActivity.this);
							AppUtil.LoginVer(ScanCertiActivity.this);
							return;
						}
						// TODO Auto-generated method stub
						ArtShownum itemArtShownum = (ArtShownum) vd.getData();
						if (itemArtShownum.getCommend_state().equals("0")) {
							imgLike.setVisibility(View.GONE);
							imgUnlike.setVisibility(View.VISIBLE);
						} else {
							imgLike.setVisibility(View.VISIBLE);
							imgUnlike.setVisibility(View.GONE);
						}
						if (itemArtShownum.getFavorite_state().equals("0")) {
							imgColl.setVisibility(View.GONE);
							imgUncoll.setVisibility(View.VISIBLE);
						} else {
							imgColl.setVisibility(View.VISIBLE);
							imgUncoll.setVisibility(View.GONE);
						}
						textsc.setText("收藏  ("
								+ String.valueOf(itemArtShownum.getFav_num())
								+ ")");
						textlike.setText("点赞("
								+ String.valueOf(itemArtShownum
										.getCommend_num()) + ")");
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}

	//回复评论
	void reqArtReplycomment() {
		VolleyBasic.getInstance(ScanCertiActivity.this).post(
				Cache.artReplycomment,
				VolleyMap.getInstance().artReplycomment(
						AppUtil.getUser().getToken(), id,
						editComment.getText().toString()), ArtistFollow.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						if (vd.getCode() == -99) {
							Config.showTip(ScanCertiActivity.this, "请先登录");
							AppUtil.Logout(ScanCertiActivity.this);
							AppUtil.LoginVer(ScanCertiActivity.this);
							return;
						}
						ArtistFollow list = (ArtistFollow) vd.getData();

						if (list.getState().equals("1")) {
							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									reqCommentData();
									editComment.setText("");
								}
							}, 1000);

							// setColLikeComment(true, textpl);
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});

	}

	// 回复某人
	void Replycomment(String commentid) {
		if (TextUtils.isEmpty(editComment.getText().toString())) {
			Config.showTip(ScanCertiActivity.this, "回复不能为空");
			return;
		}
		String contentString = "";
		if (editComment.getHint().toString()
				.contains(AppUtil.getUser().getRealname())) {
			reqArtReplycomment();
			return;
		} else {
			contentString = editComment.getHint()
					+ editComment.getText().toString();
		}

		VolleyBasic.getInstance(ScanCertiActivity.this).post(
				Cache.artAnswercomment,
				VolleyMap.getInstance().artAnswercomment(id, contentString,
						commentid), ArtistFollow.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						if (vd.getCode() == -99) {
							Config.showTip(ScanCertiActivity.this, "请先登录");
							AppUtil.Logout(ScanCertiActivity.this);
							AppUtil.LoginVer(ScanCertiActivity.this);
							return;
						}
						ArtistFollow list = (ArtistFollow) vd.getData();

						if (list.getState().equals("1")) {
							isReplyPerson = false;
							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									reqCommentData();
									editComment.setText("");
								}
							}, 1000);
							// setColLikeComment(true, textpl);
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						Log.d("log", "回复出错:" + volleyError.toString());
					}
				});

	}

	View.OnClickListener listenerGz(final String id, final Boolean setFollow) {
		return new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!AppUtil.LoginVer(mContext)) {
					reqFollow(id, setFollow);
				}
			}
		};
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

		switch (arg0.getId()) {
		//点击查看大图
		case R.id.iv_coll_img:
			Intent intent = new Intent(this, PhotoActivity.class);
			photoItem.setInfo(photoinfo);
			photoItem.setName(picname);
			photoItem.setUrl(srcImg);
			intent.putExtra("item", photoItem);
			startActivity(intent);
			break;
		//点赞
		case R.id.view_like:
			if (AppUtil.LoginVer(ScanCertiActivity.this)) {
				return;
			}
			if (imgLike.getVisibility() == View.VISIBLE) {
				reqLike(id, false);
			} else {
				reqLike(id, true);
			}

			break;

		case R.id.view_collect:
			if (AppUtil.LoginVer(ScanCertiActivity.this)) {
				return;
			}
			if (imgColl.getVisibility() == View.VISIBLE) {
				reqCollect(id, false);
			} else {
				reqCollect(id, true);
			}

			break;

		case R.id.share_collection_detail:
			if (shareItem == null) {
				Config.showTip(ScanCertiActivity.this, "请检查网络连接");
				return;
			}
			if (!TextUtils.isEmpty(codeItem.getArtistuid())) {
				AppUtil.shareWithTalk(mContext, shareItem.getTitle(), shareItem
						.getContent(), shareItem.getImageUrl(), shareItem
						.getUrl(), codeItem.getArtistuid(), AppUtil.getUser()
						.getHeadurl(), codeItem.getRealname());
			} else {
				AppUtil.showShare(mContext, shareItem.getTitle(),
						shareItem.getContent(), shareItem.getImageUrl(),
						shareItem.getUrl());
			}

			break;

		case R.id.collection_det_hideview:
			hideKeyBoard();

			break;
		case R.id.artdet_comment_edit:
			hideView.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}

	void startComment(String strPreFix) {
		editComment.setHint(strPreFix);
		editComment.setFocusable(true);
		InputMethodManager imm = (InputMethodManager) editComment.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
		mscroll.fullScroll(ScrollView.FOCUS_DOWN);
		hideView.setVisibility(View.VISIBLE);
		editComment.requestFocus();
	}

	void hideKeyBoard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		if (imm != null) {
			imm.hideSoftInputFromWindow(getWindow().getDecorView()
					.getWindowToken(), 0);
		}
		hideView.setVisibility(View.GONE);
	}

}
